package com.have.blog.base.validator.constraint;

import com.have.blog.base.validator.annotation.Range;
import org.springframework.util.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class RangeValidator implements ConstraintValidator<Range, String> {
    private long min;
    private long max;

    @Override
    public void initialize(Range constraintAnnotation) {
        min = constraintAnnotation.min();
        max = constraintAnnotation.max();
    }

    @Override
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
        if (s == null || StringUtils.isEmpty(s.trim())) {
            return min == 0;
        }
        return s.length() >= min && s.length() <= max;
    }
}
